package com.supermarket.controller;

import cn.hutool.core.util.StrUtil;
import com.supermarket.common.ResponseResult;
import com.supermarket.entity.Article;
import com.supermarket.entity.DTO.ArticleDTO;
import com.supermarket.exception.ArticleException;
import com.supermarket.service.ArticleService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private ArticleService articleService;

    /**
     * 发布文章
     *
     * @param article     文章对象
     * @param mediaFiles  媒体文件列表
     * @param mediaTypes  媒体类型列表
     * @return 包含文章ID的响应结果
     */
    @PostMapping("/publish")
    public ResponseResult<Integer> publishArticle(
            @RequestPart("article") Article article,
            @RequestPart(value = "mediaFiles", required = false) List<MultipartFile> mediaFiles,
            @RequestParam(value = "mediaTypes", required = false) List<String> mediaTypes) {
        
        try {
            if (StrUtil.isBlank(article.getContent())) {
                return ResponseResult.error(400, "文章内容不能为空");
            }

            System.out.println("article: " + article);
            System.out.println("mediaFiles: " + mediaFiles);
            System.out.println("mediaTypes: " + mediaTypes);

            if (mediaFiles != null && !mediaFiles.isEmpty() && mediaTypes != null && !mediaTypes.isEmpty()) {
                for (String type : mediaTypes) {
                    if (!StrUtil.equalsAny(type, "IMAGE", "VIDEO")) {
                        return ResponseResult.error(400, "媒体类型错误");
                    }
                }
            }

            Integer articleId = articleService.publishArticle(article, mediaFiles, mediaTypes);
            return ResponseResult.success(articleId);
        } catch (ArticleException e) {
            return ResponseResult.error(400, e.getMessage());
        } catch (IOException e) {
            return ResponseResult.error(500, "文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 更新文章
     *
     * @param article 文章对象
     * @return 包含操作结果的响应结果
     */
    @PutMapping("/update")
    public ResponseResult<String> updateArticle(@RequestBody Article article) {
        try {
            if (article.getId() == null) {
                return ResponseResult.error(400, "文章ID不能为空");
            }
            
            int result = articleService.updateArticle(article);
            if (result > 0) {
                return ResponseResult.success("文章更新成功");
            } else {
                return ResponseResult.error(400, "文章更新失败");
            }
        } catch (ArticleException e) {
            return ResponseResult.error(400, e.getMessage());
        }
    }

    /**
     * 删除文章
     *
     * @param id 文章ID
     * @return 包含操作结果的响应结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseResult<String> deleteArticle(@PathVariable Integer id) {
        try {
            int result = articleService.deleteArticle(id);
            if (result > 0) {
                return ResponseResult.success("文章删除成功");
            } else {
                return ResponseResult.error(400, "文章删除失败");
            }
        } catch (Exception e) {
            return ResponseResult.error(500, "删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取文章详情
     *
     * @param id 文章ID
     * @return 包含文章详情的响应结果
     */
    @GetMapping("/detail/{id}")
    public ResponseResult<ArticleDTO> getArticleDetail(@PathVariable Integer id) {
        ArticleDTO article = articleService.getArticleDetail(id);
        if (article != null) {
            return ResponseResult.success(article);
        } else {
            return ResponseResult.error(404, "文章不存在");
        }
    }
    
    /**
     * 获取文章详情（带点赞状态）
     *
     * @param id 文章ID
     * @param userId 用户ID（可选）
     * @return 包含文章详情和点赞状态的响应结果
     */
    @GetMapping("/detail-with-like/{id}")
    public ResponseResult<Map<String, Object>> getArticleDetailWithLikeStatus(
            @PathVariable Integer id,
            @RequestParam(required = false) Integer userId) {
        
        Map<String, Object> result = articleService.getArticleDetailWithLikeStatus(id, userId);
        if (result != null) {
            return ResponseResult.success(result);
        } else {
            return ResponseResult.error(404, "文章不存在");
        }
    }

    /**
     * 检查用户是否点赞过文章
     *
     * @param id 文章ID
     * @param userId 用户ID
     * @return 包含点赞状态的响应结果
     */
    @GetMapping("/check-like/{id}")
    public ResponseResult<Boolean> checkUserLiked(
            @PathVariable Integer id,
            @RequestParam Integer userId) {
        
        boolean hasLiked = articleService.checkUserLiked(id, userId);
        return ResponseResult.success(hasLiked);
    }

    /**
     * 分页查询文章列表
     *
     * @param pageNum  当前页码
     * @param pageSize 每页显示条数
     * @param userId   用户ID（可选）
     * @param status   状态（可选）
     * @return 包含分页文章列表的响应结果
     */
    @GetMapping("/list")
    public ResponseResult<Map<String, Object>> getArticleList(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "status", required = false) String status) {
        
        Map<String, Object> result = articleService.getArticlesWithPagination(pageNum, pageSize, userId, status);
        return ResponseResult.success(result);
    }

    /**
     * 获取用户发布的文章
     *
     * @param userId 用户ID
     * @return 包含用户文章列表的响应结果
     */
    @GetMapping("/user/{userId}")
    public ResponseResult<List<ArticleDTO>> getUserArticles(@PathVariable Integer userId) {
        List<ArticleDTO> articles = articleService.getUserArticles(userId);
        return ResponseResult.success(articles);
    }

    /**
     * 获取热门文章
     *
     * @param limit 获取数量，默认为10
     * @return 包含热门文章列表的响应结果
     */
    @GetMapping("/hot")
    public ResponseResult<List<ArticleDTO>> getHotArticles(
            @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        List<ArticleDTO> articles = articleService.getHotArticles(limit);
        return ResponseResult.success(articles);
    }

    /**
     * 根据状态获取文章
     *
     * @param status 文章状态
     * @return 包含文章列表的响应结果
     */
    @GetMapping("/status/{status}")
    public ResponseResult<List<ArticleDTO>> getArticlesByStatus(@PathVariable String status) {
        List<ArticleDTO> articles = articleService.getArticlesByStatus(status);
        return ResponseResult.success(articles);
    }

    /**
     * 更新文章（含媒体文件处理）
     *
     * @param article        文章对象
     * @param deleteMediaIds 要删除的媒体ID列表（可选）
     * @param mediaFiles     新增的媒体文件列表（可选）
     * @param mediaTypes     新增的媒体类型列表（可选）
     * @return 包含操作结果的响应结果
     */
    @PostMapping("/update-with-media")
    public ResponseResult<String> updateArticleWithMedia(
            @RequestPart("article") Article article,
            @RequestPart(value = "deleteMediaIds", required = false) List<Integer> deleteMediaIds,
            @RequestPart(value = "mediaFiles", required = false) List<MultipartFile> mediaFiles,
            @RequestParam(value = "mediaTypes", required = false) List<String> mediaTypes) {
        
        try {
            if (article.getId() == null) {
                return ResponseResult.error(400, "文章ID不能为空");
            }
            
            if (StrUtil.isBlank(article.getContent())) {
                return ResponseResult.error(400, "文章内容不能为空");
            }
            
            // 验证媒体类型
            if (mediaFiles != null && !mediaFiles.isEmpty() && mediaTypes != null && !mediaTypes.isEmpty()) {
                for (String type : mediaTypes) {
                    if (!StrUtil.equalsAny(type, "IMAGE", "VIDEO")) {
                        return ResponseResult.error(400, "媒体类型错误");
                    }
                }
            }
            
            boolean result = articleService.updateArticleWithMedia(article, deleteMediaIds, mediaFiles, mediaTypes);
            if (result) {
                return ResponseResult.success("文章更新成功");
            } else {
                return ResponseResult.error(400, "文章更新失败");
            }
        } catch (ArticleException e) {
            return ResponseResult.error(400, e.getMessage());
        } catch (IOException e) {
            return ResponseResult.error(500, "文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            return ResponseResult.error(500, "更新失败: " + e.getMessage());
        }
    }

    /**
     * 批量获取多篇文章详情
     *
     * @param ids 文章ID列表，以逗号分隔
     * @return 包含多篇文章详情的响应结果
     */
    @GetMapping("/batch")
    public ResponseResult<Map<Integer, ArticleDTO>> getBatchArticleDetails(@RequestParam("ids") String ids) {
        try {
            // 解析文章ID列表
            List<Integer> idList = StrUtil.split(ids, ',')
                    .stream()
                    .map(Integer::parseInt)
                    .toList();
            
            if (idList.isEmpty()) {
                return ResponseResult.error(400, "文章ID列表不能为空");
            }
            
            Map<Integer, ArticleDTO> articlesMap = articleService.getBatchArticleDetails(idList);
            return ResponseResult.success(articlesMap);
        } catch (NumberFormatException e) {
            return ResponseResult.error(400, "无效的文章ID格式");
        }
    }
    
    /**
     * 批量获取多篇文章详情（带点赞状态）
     *
     * @param ids 文章ID列表，以逗号分隔
     * @param userId 用户ID（可选）
     * @return 包含多篇文章详情和点赞状态的响应结果
     */
    @GetMapping("/batch-with-like")
    public ResponseResult<Map<Integer, Map<String, Object>>> getBatchArticleDetailsWithLikeStatus(
            @RequestParam("ids") String ids,
            @RequestParam(required = false) Integer userId) {
        try {
            // 解析文章ID列表
            List<Integer> idList = StrUtil.split(ids, ',')
                    .stream()
                    .map(Integer::parseInt)
                    .toList();
            
            if (idList.isEmpty()) {
                return ResponseResult.error(400, "文章ID列表不能为空");
            }
            
            Map<Integer, Map<String, Object>> result = articleService.getBatchArticleDetailsWithLikeStatus(idList, userId);
            return ResponseResult.success(result);
        } catch (NumberFormatException e) {
            return ResponseResult.error(400, "无效的文章ID格式");
        } catch (ArticleException e) {
            return ResponseResult.error(400, e.getMessage());
        }
    }
} 